package com.kefu.chat.service;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.kefu.chat.mapper.ChatSessionMapper;
import com.kefu.chat.model.ChatAdmin;
import com.kefu.chat.vo.ChatTimeSharingRptSearchVo;
import com.kefu.chat.vo.ChatTimeSharingRptVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.util.Assert;
import com.kefu.common.util.DivUtil;
import com.kefu.sys.mapper.SysUserMapper;
import com.kefu.sys.model.SysUser;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kefu.chat.mapper.ChatRptAdminWorkMapper;
import com.kefu.chat.vo.ChatRptAdminWork;
import com.kefu.chat.vo.ChatRptAdminWorkSearchVo;
import com.kefu.common.service.AbstractKefuService;

/**
 * @author CodeGenerator
 * @date 2021/04/28
 */
@Service
@Transactional
public class ChatRptAdminWorkService  extends AbstractKefuService<ChatRptAdminWork>  {
    @Autowired
    protected ChatRptAdminWorkMapper chatRptAdminWorkMapper;
	@Resource
	private ChatSessionMapper chatSessionMapper;
	@Resource
	private SysUserMapper sysUserMapper;
	@Autowired
	ChatCacheService chatCacheService;

	 
	public List<ChatRptAdminWork> selectGroupList(ChatRptAdminWorkSearchVo search) {
		return chatRptAdminWorkMapper.selectGroupList(search);
	}

	public Page<ChatTimeSharingRptVo> timeSharingRpt(ChatTimeSharingRptSearchVo search) {
		Page<SysUser> userPage = new Page<>(search.getPageNo(), search.getPageSize(), true);
		userPage = sysUserMapper.selectPage(userPage,
				Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getTenantId, KefuContext.getKefuContext().getTenantId()));
		Function<SysUser, ChatTimeSharingRptVo> fun=sys->BeanUtil.toBean(sys, ChatTimeSharingRptVo.class);
		Page<ChatTimeSharingRptVo> page = (Page<ChatTimeSharingRptVo>) userPage.convert(fun);
		List<ChatTimeSharingRptVo> records = Lists.newArrayList();
		for (SysUser user : userPage.getRecords()) {
			ChatTimeSharingRptVo rptVo = new ChatTimeSharingRptVo();
			rptVo.setAdminId(user.getUserId());
			rptVo.setAdminName(user.getUserName());
			Map<String,Object> param=Maps.newHashMap();
			param.put("startTime", search.getStartTime());
			param.put("endTime", search.getEndTime());
			param.put("tenantId", KefuContext.getTid());
			if (DateUtil.isSameDay(DateUtil.date(search.getStartTime()),DateUtil.date(search.getEndTime()))) {
				param.put("groupType", "date");
				rptVo.setShowType(1);
			} else {
				param.put("groupType", "hour");
				rptVo.setShowType(2);
			}
			List<ChatTimeSharingRptVo.ChatTimeSharingItemRptVo> list = chatSessionMapper.staticsByDate(param);

			rptVo.setItems(list);
		}
		page.setRecords(records);
		return page;
	}

	public void exportTimeSharingRpt(ChatTimeSharingRptSearchVo search, HttpServletResponse response) throws IOException {
		Page<ChatTimeSharingRptVo> list = timeSharingRpt(search);
		List<Object[]> exportList = new ArrayList<>();
		Object[] title = {msg("坐席"), msg("时间段"), msg("接待数")};
		exportList.add(title);
		for (ChatTimeSharingRptVo i : list.getRecords()) {
			for (ChatTimeSharingRptVo.ChatTimeSharingItemRptVo item : i.getItems()) {
				Object[] row = {i.getAdminName(),
						(1 == i.getShowType()) ? item.getResultHour() : item.getResultDate(), item.getSessionCount()};
				exportList.add(row);
			}
		}
		csvWriter(exportList, response);
	}

	public List<Object[]> adminWorkExport(ChatRptAdminWorkSearchVo search) {
		Assert.isNull(search.getStartTime(), "开始时间不能为空！");
		Assert.isNull(search.getEndTime(), "结束时间不能为空！");
		search.setTenantId(KefuContext.getKefuContext().getTenantId());
		List<ChatRptAdminWork> list = selectGroupList(search);
		List<Object[]> exportList = new ArrayList<>();
		Object[] title = {msg("客服名称"), msg("在线时长"), msg("忙碌时长"),
				msg("接待会话数"), msg("有效会话数"), msg("无效会话数"), msg("转接会话数"),
				msg("客服消息数"), msg("客户消息数"), msg("回复率"),
				msg("平均会话时长"), msg("首次响应时长"), msg("平均响应时长"),
				msg("人工评价解决"), msg("客服1星评价"), msg("客服2星评价"),
				msg("客服3星评价"), msg("客服4星评价"), msg("客服5星评价")};
		exportList.add(title);
		for (ChatRptAdminWork i : list) {
			if (search.getEndTime() >= System.currentTimeMillis()) {
				ChatAdmin admin = chatCacheService.getAdmin(i.getAdminId());
				if (admin != null) {
					if (admin.getStatus() == 1) {
						int statusDuration = (int) (System.currentTimeMillis() - admin.getStatusTime()) / 1000;
						i.setOnlineStatusDuration(i.getOnlineStatusDuration() + statusDuration);
					} else if (admin.getStatus() == 2) {
						int statusDuration = (int) (System.currentTimeMillis() - admin.getStatusTime()) / 1000;
						i.setBusyStatusDuration(i.getBusyStatusDuration() + statusDuration);
					}
				}
			}
			Object[] row = {i.getAdminName(), DateUtil.secondToTime(i.getOnlineStatusDuration()), DateUtil.secondToTime(i.getBusyStatusDuration()),
					i.getAcceptCount(), i.getUserSendToAdmin(), i.getAcceptCount() - i.getUserSendToAdmin(), i.getTransferCount(),
					i.getAdminMsgCount(), i.getUserAdminMsgCount(), DivUtil.percent(i.getAdminSendToUser(), i.getAcceptCount()),
					DateUtil.secondToTime(divInt(i.getTotalTime(), i.getAcceptCount())), DateUtil.secondToTime(divInt(i.getFirstReplyDuration(), i.getAdminSendToUser())), DateUtil.secondToTime(divInt(i.getAvgReplyDuration(), i.getAdminSendToUser())),
					i.getAdminSolve(), i.getAdminStar1(), i.getAdminStar2(),
					i.getAdminStar3(), i.getAdminStar4(), i.getAdminStar5()
			};
			exportList.add(row);
		}
		return exportList;
	}

	int divInt(int a, int b) {
		if (b == 0) {
			return 0;
		} else {
			return a / b;
		}
	}

	double divDouble(int a, int b) {
		if (b == 0) {
			return 0;
		} else {
			return a * 1.0 / b;
		}
	}
}
